﻿using COSXML;
using COSXML.Auth;
using COSXML.Model.Object;
using System;
using System.Collections.Generic;
using System.Text;

namespace OtherLib.TenXun
{
    public static class CosUtil
    {
        readonly static CosXml cosXml;
        static CosUtil()
        {
            var config = new CosXmlConfig.Builder()
                          .IsHttps(true)  //设置默认 HTTPS 请求
                          .SetRegion(TenXunConfig.Cos_Region)  //设置一个默认的存储桶地域
                          .SetDebugLog(true)  //显示日志
                          .Build();  //创建 CosXmlConfig 对象

            var cosCredentialProvider = new DefaultQCloudCredentialProvider(TenXunConfig.SecretId, TenXunConfig.SecretKey, TenXunConfig.Cos_DurationSecond);

            cosXml = new CosXmlServer(config, cosCredentialProvider);
        }

        public static string UploadObject(string fileFullPath,byte[] bytes)
        {
            try
            {
                //string key = "exampleobject"; //对象键
                //string srcPath = @"temp-source-file";//本地文件绝对路径
                PutObjectRequest request = new PutObjectRequest(TenXunConfig.Cos_Bucket, fileFullPath, bytes);
                //设置进度回调
                request.SetCosProgressCallback(delegate (long completed, long total)
                {
                    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                });
                //执行请求
                PutObjectResult result = cosXml.PutObject(request);
                //对象的 eTag
                string eTag = result.eTag;

                return $"{TenXunConfig.Cos_Domain}/{fileFullPath}";
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
            return null;
        }
    }
}
